/**
 * 
 */
package org.softTank.BpelTranslator.Impl;

import javax.xml.namespace.QName;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.softTank.BcpModel.BcpExpression;
import org.softTank.BpelModel.TBooleanExpr;
import org.softTank.BpelTranslator.BoolExpressionParser;

/**
 * @author Yuzone
 * 
 */
public class BoolExpressionParserImpl implements BoolExpressionParser {

	private int count;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.softTank.BpelTranslator.BoolExpressionParser#parseExpression(org.
	 * softTank.BcpModel.BcpExpression)
	 */
	@Override
	public TBooleanExpr parseExpression(BcpExpression value) {
		count = 2;
		TBooleanExpr expr = new TBooleanExpr();
		if (value == null)
			return expr;
		String operation = value.getOperation() != null ? value.getOperation()
				: "";
		expr.getContent().add(
				parseValue(value.getValueA(), expr) + operation
						+ parseValue(value.getValueB(), expr));

		return expr;
	}

	private String parseValue(String value, TBooleanExpr expr) {
		JSONObject obj = new JSONObject();
		try {
			obj = JSONObject.fromObject(value);
		} catch (JSONException e) {
			return value;
		}
		if (obj.isNullObject())
			return "";
		StringBuffer sb = new StringBuffer();
		if (!obj.getString("variable").equals("")) {
			sb.append("$" + obj.get("variable"));
		}
		if (!obj.getString("part").equals("")) {
			sb.append("." + obj.get("part"));
		}
		if (!obj.getString("parameter").equals("")) {
			sb.append("/ns" + (count++) + ":" + obj.get("parameter"));
		}
		expr.getOtherAttributes().put(
				new QName(obj.getString("namespace"), "ens"), "");
		return sb.toString();
	}

}
